package com.speedchina.permission.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.speedchina.permission.dao.sys.UserDao;
import com.speedchina.permission.domain.sys.entity.Role;
import com.speedchina.permission.domain.sys.entity.User;
import com.speedchina.permission.service.sys.ResourceService;
import com.speedchina.permission.service.sys.RoleService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author ：Winter
 * @description：TODO
 * @date ：2021-07-15 17:01
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    UserDao baseMapper;

    @Resource
    RoleService roleService;

    @Resource
    ResourceService resourceService;

    public User getByUserName(String username) {
        List<User> users = baseMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getUsername,username));
        return users.isEmpty()?null:users.get(0);
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getByUserName(username);
        Set<GrantedAuthority> authorities = new HashSet<>();

        List<Role> roles = roleService.findByUserId(user);
        for (Role role : roles){
            authorities.add(new SimpleGrantedAuthority(role.getRoleKey()));
        }

        Set<String> resources = resourceService.getPermissions(user.getId());
        for (String resource : resources){
            authorities.add(new SimpleGrantedAuthority(resource));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
